import { Injectable, OnModuleInit, Logger } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { Repository } from "typeorm";
import * as bcrypt from "bcrypt";
import { User } from "./modules/user/entities/user.entity";

@Injectable()
export class AppService implements OnModuleInit {
	private readonly logger = new Logger(AppService.name);

	constructor(
		@InjectRepository(User)
		private userRepository: Repository<User>
	) {}

	async onModuleInit() {
		await this.createAdminIfNotExists();
	}

	async createAdminIfNotExists() {
		try {
			// 检查管理员是否已存在
			const adminExists = await this.userRepository.findOne({
				where: { username: "admin" },
			});

			if (!adminExists) {
				this.logger.log("创建管理员账户...");

				// 密码加密
				const salt = await bcrypt.genSalt();
				const hashedPassword = await bcrypt.hash("admin123", salt);

				// 创建管理员用户
				const adminUser = this.userRepository.create({
					username: "admin",
					password: hashedPassword,
					nickname: "系统管理员",
					role: "admin",
					status: "正常",
					points: 9999,
				});

				await this.userRepository.save(adminUser);
				this.logger.log("管理员账户创建成功！");
			} else {
				this.logger.log("管理员账户已存在");
			}
		} catch (error) {
			this.logger.error("创建管理员账户失败", error);
		}
	}
}
